<script setup lang="ts">
import category from "@/components/Category/index.vue";
import useCategory from "@/store/category.ts";
import { nextTick, onBeforeUnmount, reactive, ref, watch } from "vue";
import { reqAttr, reqAddOrUpdateAttr, reqDeleteAttr } from "@/api/product/attr";
import {
  AttrResType,
  AttrType,
  AttrValueType,
} from "@/api/product/attr/type.ts";

import { ElMessage } from "element-plus";
import "element-plus/theme-chalk/el-message.css";

const categoryStore = useCategory();
const attrList = ref<AttrType[]>([]);
let inputArr = ref<any>([]);

// 新增属性的参数
let addParams = reactive<AttrType>({
  categoryId: null,
  categoryLevel: 3,
  attrValueList: [],
  attrName: "",
});

// 切换卡片区的内容
let scene = ref<number>(0);

const changeScene = () => {
  // 清空添加页的数据
  Object.assign(addParams, {
    categoryId: categoryStore.c3ID,
    categoryLevel: 3,
    attrValueList: [],
    attrName: "",
    id: null,
  });

  scene.value = 1;
};

watch(
  () => categoryStore.c3ID,
  () => {
    getAttr();
  },
);

const getAttr = async () => {
  // 清空table
  attrList.value = [];

  let { c1ID, c2ID, c3ID } = categoryStore;
  if (!c3ID) return;
  const result: AttrResType = await reqAttr(c1ID, c2ID, c3ID);
  if (result.data.code === 200) {
    attrList.value = result.data.data;
  }
};

const handleEdit = (row: AttrType) => {
  scene.value = 1;
  // 深拷贝
  Object.assign(addParams, JSON.parse(JSON.stringify(row)));
};
const handleDelete = async (index: number) => {
  let result = await reqDeleteAttr(index);
  if (result.data.code === 200) {
    ElMessage.success("删除成功");
    await getAttr();
  } else {
    ElMessage.error("删除失败");
  }
};

const addAttrValue = () => {
  addParams.attrValueList.push({ valueName: "", flag: true });

  nextTick(() => {
    inputArr.value[inputArr.value.length - 1].focus();
  });
};

const saveAttrs = async () => {
  const result = await reqAddOrUpdateAttr(addParams);
  if (result.data.code === 200) {
    ElMessage({
      type: "success",
      message: addParams.id ? "修改成功" : "添加成功",
    });
    scene.value = 0;
    await getAttr();
  } else {
    ElMessage({
      type: "error",
      message: addParams.id ? "修改失败" : "添加失败",
    });
  }
};

// 切换到查看
const toLook = (row: AttrValueType, $index: number) => {
  if (row.valueName.trim() === "") {
    addParams.attrValueList.splice($index, 1);
    ElMessage.warning("属性值不能为空");
    return;
  }

  // 属性值是否重复，返回重复的值
  let repeat = addParams.attrValueList.find((item) => {
    // 排除自己
    if (item != row) return item.valueName === row.valueName;
  });
  if (repeat) {
    addParams.attrValueList.splice($index, 1);
    ElMessage.warning("属性值不能重复");
  }
  row.flag = false;
};

const toEdit = (row: AttrValueType, $index: number) => {
  row.flag = true;
  // 聚焦
  nextTick(() => {
    inputArr.value[$index].focus();
  });
};

onBeforeUnmount(() => {
  // 切换路由时。清空仓库数据
  categoryStore.c1ID = null;
  categoryStore.c2ID = null;
  categoryStore.c3ID = null;
});
</script>

<template>
  <div>
    <category :scene="scene" />

    <el-card style="margin-top: 10px">
      <div v-show="scene == 0">
        <el-button
          type="primary"
          icon="plus"
          :disabled="!categoryStore.c3ID"
          @click="changeScene"
          >添加属性</el-button
        >
        <el-table border style="margin: 10px 0" :data="attrList">
          <el-table-column
            label="序号"
            type="index"
            width="80px"
            align="center"
            prop="id"
          ></el-table-column>
          <el-table-column
            label="属性名"
            align="center"
            prop="attrName"
          ></el-table-column>
          <el-table-column label="属性值" align="center">
            <template #default="{ row }">
              <el-tag
                style="margin: 5px"
                v-for="item in row.attrValueList"
                :key="item.id"
                >{{ item.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="{ row }">
              <el-button type="primary" icon="Edit" @click="handleEdit(row)" />
              <el-button
                type="danger"
                icon="Delete"
                @click="handleDelete(row.id)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 添加属性 -->
      <div v-show="scene == 1">
        <el-form inline>
          <el-form-item label="属性名">
            <el-input v-model="addParams.attrName" />
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="Plus"
          :disabled="!addParams.attrName"
          @click="addAttrValue"
          >添加属性值
        </el-button>

        <el-table
          border
          style="margin-top: 10px"
          :data="addParams.attrValueList"
        >
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
          ></el-table-column>
          <el-table-column label="属性值" align="center" width="300px">
            <template #default="{ row, $index }">
              <el-input
                :ref="(vc: any) => (inputArr[$index] = vc)"
                @blur="toLook(row, $index)"
                v-if="row.flag"
                v-model="row.valueName"
              />
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="150px">
            <template #default="{ row, $index }">
              <el-button
                type="danger"
                icon="Delete"
                @click="addParams.attrValueList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-button
          type="primary"
          :disabled="addParams.attrValueList.length === 0"
          @click="saveAttrs"
          >保存</el-button
        >
        <el-button type="info" @click="scene = 0">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss"></style>
